<template>
  <!-- 新增采购页面 -->
  <div class="app-container">
    <!-- 按钮 开始-->
    <el-card class="box-card">
      <div style="text-align:right;">
        <el-button type="primary" icon="el-icon-plus" :disabled="isSubmit" size="small" @click="handleAddMedicines">添加药品</el-button>
        <el-button type="success" icon="el-icon-s-operation" :disabled="isSubmit" size="small" @click="handleBatchSet">批量设置</el-button>
        <el-button type="warning" icon="el-icon-check" :disabled="isSubmit" size="small" @click="handleSubmit">暂存</el-button>
        <el-button type="danger" icon="el-icon-finished" :disabled="isSubmit" size="small" @click="handleSubmitAndAudit">提交审核</el-button>
      </div>
    </el-card>
    <!-- 按钮 结束-->
    <!-- 主表单开始 -->
    <el-card class="box-card">
      <el-form ref="form" :rules="rules" :model="form" :inline="true" label-width="68px">
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-form-item label="单据号" prop="purchaseId">
              <el-input
                v-model="form.purchaseId"
                placeholder="请输入单据号"
                :disabled="true"
                size="small"
                style="width:220px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item label="供应商" prop="providerId">
              <el-select
                v-model="form.providerId"
                placeholder="请选择供应商"
                size="small"
                style="width:220px"
              >
                <el-option
                  v-for="provider in providerOptions"
                  :key="provider.providerId"
                  :value="provider.providerId"
                  :label="provider.providerName"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="总批发额" prop="purchaseTradeTotalAmount">
              <el-input
                v-model="form.purchaseTradeTotalAmount"
                placeholder="请输入总批发额"
                :disabled="true"
                size="small"
                style="width:220px"
              />
              {{ form.purchas }}
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 主表单结束 -->
    <!-- 详情数据表格开始 -->
    <el-card class="box-card">
      <el-table
        :data="purchaseItemList"
        class="tb-edit"
        style="width:100%"
        highlight-current-row
        border
      >
        <el-table-column label="药品Id" align="center" prop="medicinesId" />
        <el-table-column label="药品名称" align="center" prop="medicinesName" />
        <el-table-column label="换算规则" align="center" prop="conversion">
          <template slot-scope="scope">
            <span>{{ scope.row.conversion }}{{ scope.row.unit }}</span>
          </template>
        </el-table-column>
        <el-table-column width="280" label="生产厂家" align="center" show-overflow-tooltip prop="producterId" :formatter="producterFormatter" />
        <el-table-column label="数量" width="200" align="center" prop="purchaseNumber">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.purchaseNumber"
              size="small"
              :step="1"
            />
            <!-- step 设置每次增加的步长为1 -->
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="批发价" width="200" align="center" prop="tradePrice">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.tradePrice"
              size="small"
              :step="0.1"
              :precision="2"
            />
            <!-- precision保留两位小数 -->
            <!-- step 设置每次增加的步长为0.1 -->
          </template>
        </el-table-column>
        <el-table-column label="批发额" align="center" prop="tradeTotalAmount">
          <template slot-scope="scope">
            <span>{{ scope.row.tradeTotalAmount|rounding }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次号" align="center" prop="batchNumber">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.batchNumber"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="danger" :disabled="isSubmit" @click="handleDelele(scope.$index,scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
    </el-card>
    <!-- 详情数据表格结束 -->

    <!-- 选择添加药品弹出层开始 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1100px"
      center
      append-to-body
    >
      <!-- 查询条件开始 -->
      <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">

        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入关键字"
            clearable
            size="small"
            style="width:180px"
          />
        </el-form-item>
        <el-form-item label="药品类型" prop="medicinesType">
          <el-select
            v-model="queryParams.medicinesType"
            placeholder="药品类型"
            clearable
            size="small"
            style="width:180px"
          >
            <el-option
              v-for="dict in medicinesTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="处方类型" prop="prescriptionType">
          <el-select
            v-model="queryParams.prescriptionType"
            placeholder="处方类型"
            clearable
            size="small"
            style="width:180px"
          >
            <el-option
              v-for="dict in prescriptionTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <!-- 查询条件结束 -->

      <el-table ref="medicinesTableList" v-loading="loading" border :data="medicinesTableList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="药品ID" align="center" prop="medicinesId" />
        <el-table-column label="药品名称" align="center" prop="medicinesName" />
        <el-table-column label="药品编号" align="center" prop="medicinesNumber" />
        <el-table-column label="生产厂家" width="280px" align="center" prop="producterId" :formatter="producterFormatter" />
        <el-table-column label="药品类型" align="center" prop="medicinesType" :formatter="medicinesTypeFormatter" />
        <el-table-column label="处方类型" align="center" prop="prescriptionType" :formatter="prescriptionTypeFormatter" />
        <el-table-column label="关键字" align="center" prop="keywords" />
      </el-table>
      <!-- 药品的数据表格结束 -->
      <!-- 分页控件开始 -->
      <el-pagination
        v-show="total>0"
        :current-page="queryParams.pageNum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    <!-- 分页控件结束 -->
    </el-dialog>
    <!-- 选择添加药品弹出层结束 -->
    <!-- 批量设置的弹出层开始 -->
    <el-dialog
      :title="title"
      :visible.sync="batchSetOpen"
      width="500px"
      center
      append-to-body
    >
      <el-form ref="batchSetForm" :model="batchSetForm" label-width="100px">
        <el-form-item label="数量" prop="purchaseNumber" width="100%">
          <el-input-number v-model="batchSetForm.purchaseNumber" placeholder="请输入数量" size="small" />
        </el-form-item>
        <el-form-item label="批发价格" prop="tradePrice">
          <el-input-number
            v-model="batchSetForm.tradePrice"
            placeholder="请输入批发价格"
            size="small"
            :precision="2"
          />
          <!-- precision保留两位小数 -->
        </el-form-item>
        <el-form-item label="批次号" prop="batchNumber">
          <el-input v-model="batchSetForm.batchNumber" placeholder="请输入批次号" size="small" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="batchSetForm.remark" placeholder="请输入备注" size="small" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleBatchSetSubmit">确定</el-button>
        <el-button @click="cancelBatchSet">取消</el-button>
      </span>
    </el-dialog>
    <!-- 批量设置的弹出层结束 -->

    <!-- 测试数据 开始 -->
    <!-- <div>
      {{ purchaseItemList }}
    </div>
    <hr>
    <div>
      {{ selectMedicines }}
    </div> -->
    <!-- 测试数据 结束 -->
  </div>
</template>

<script>
import { selectAllProvider } from '@/api/erp/provider'
import { generatePurchaseId, addPurchase, addPurchaseToAudit } from '@/api/erp/purchase'
import { selectAllProducter } from '@/api/erp/producter'
import { listMedicinesForPage } from '@/api/erp/medicines'
export default {
  // 过滤器
  filters: {
    // 保留两位小数
    rounding(value) {
      return value.toFixed(2)
    }
  },
  data() {
    return {
      // 总条数
      total: 0,
      // 选择添加药品弹出层标题
      title: '',
      // 是否打开弹出层
      open: false,
      // 选择添加药品查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keywords: undefined,
        medicinesType: undefined,
        prescriptionType: undefined

      },
      // 药品信息列表
      medicinesTableList: [],
      // 加载效果
      loading: false,
      // 是否已提交审核
      isSubmit: false,
      // 主表单表单数据
      form: {
        purchaseId: undefined,
        providerId: undefined,
        purchaseTradeTotalAmount: undefined
      },
      // 供应商列表
      providerOptions: [],
      // 生产厂家列表
      producterOptions: [],
      // 药品类型列表
      medicinesTypeOptions: [],
      // 处方类型列表
      prescriptionTypeOptions: [],
      // 采购详情列表
      purchaseItemList: [
        // {
        //   medicinesId: 11,
        //   medicinesName: '双黄连',
        //   conversion: 1,
        //   producterId: 1,
        //   purchaseNumber: 10,
        //   unit: 'g',
        //   tradePrice: 10.00,
        //   tradeTotalAmount: 100.00,
        //   batchNumber: '1',
        //   remark: '很好'
        // },
        // {
        //   medicinesId: 22,
        //   medicinesName: '双黄连',
        //   conversion: 1,
        //   producterId: 2,
        //   purchaseNumber: 10,
        //   unit: 'g',
        //   tradePrice: 10.00,
        //   tradeTotalAmount: 100.00,
        //   batchNumber: '1',
        //   remark: '很好'
        // }

      ],
      // 弹出层选中的药品
      selectMedicines: [],
      // 批量设置的是否弹出
      batchSetOpen: false,
      // 批量设置的表单数据
      batchSetForm: {
        purchaseNumber: 0,
        tradePrice: 0.00,
        batchNumber: '',
        remark: ''
      },
      // 表单校验规则
      rules: {
        providerId: [
          { required: true, message: '请选择供应商', trigger: 'blur' }
        ]
      }
    }
  },
  // 监听器
  watch: {
    // 监听purchaseItemList里面的数据变化，更新批发额及总批发额
    purchaseItemList: {
      handler: function() {
        // 重置一下总批发额
        this.form.purchaseTradeTotalAmount = 0.00
        // 遍历用户当前选择的药品信息列表
        this.purchaseItemList.filter(item => {
          // console.log(item)
          // 设置批发额为 数量*批发价
          item.tradeTotalAmount = item.tradePrice * item.purchaseNumber
          // 设置总批发额
          // console.log(this.form.purchaseTradeTotalAmount)
          this.form.purchaseTradeTotalAmount += item.tradeTotalAmount
          // console.log(this.form.purchaseTradeTotalAmount)
        })
      },
      // 解决监听不生效的问题
      deep: true
    }
  },
  created() {
    // 查询供应商列表数据
    selectAllProvider().then(res => {
      this.providerOptions = res.data
    })
    // 生成订单id
    generatePurchaseId().then(res => {
      this.form.purchaseId = res.data
    })
    // 查询生产厂家列表
    selectAllProducter().then(res => {
      this.producterOptions = res.data
    })
    // 查询药品分类字典数据
    this.getDataByType('his_medicines_type').then(res => {
      this.medicinesTypeOptions = res.data
    })
    // 查询药品处方分类字典数据
    this.getDataByType('his_prescription_type').then(res => {
      this.prescriptionTypeOptions = res.data
    })
  },
  methods: {
    // 添加药品
    handleAddMedicines() {
      // 赋值标题
      this.title = '选择添加药品信息'
      // 打开
      this.open = true
      // 查询药品信息
      this.getMedicinesList()
    },
    // 批量设置
    handleBatchSet() {
      // 重置一下批量设置的表单信息
      // this.resetForm('batchSetForm')
      this.batchSetOpen = true
      this.title = '批量设置'
    },
    // 暂存
    handleSubmit() {
      const tx = this
      if (tx.purchaseItemList.length > 0) {
        tx.$refs['form'].validate((valid) => {
          if (valid) {
            // 组装要提交到后台的数据
            const purchaseObj = { 'purchaseDto': tx.form, 'purchaseItemDtos': tx.purchaseItemList }
            addPurchase(purchaseObj).then(res => {
              tx.msgSuccess('暂存成功')
            }).catch(() => {
              tx.msgError('暂存失败')
            })
          }
        })
      } else {
        tx.msgError('药品数据项不能为空')
      }
    },
    // 提交审核
    handleSubmitAndAudit() {
      const tx = this
      if (tx.purchaseItemList.length > 0) {
        tx.$refs['form'].validate((valid) => {
          if (valid) {
            // 组装要提交到后台的数据
            const purchaseObj = { 'purchaseDto': tx.form, 'purchaseItemDtos': tx.purchaseItemList }
            addPurchaseToAudit(purchaseObj).then(res => {
              tx.msgSuccess('提交成功')
              // 禁用按钮
              tx.isSubmit = true
            }).catch(() => {
              tx.msgError('提交失败')
            })
          }
        })
      } else {
        tx.msgError('药品数据项不能为空')
      }
    },
    // 翻译生产厂家
    producterFormatter(row) {
      let name = ''
      this.producterOptions.filter(item => {
        if (parseInt(row.producterId) === parseInt(item.producterId)) {
          name = item.producterName
        }
      })
      return name
    },
    // 翻译药品类型
    medicinesTypeFormatter(row) {
      return this.selectDictLabel(this.medicinesTypeOptions, row.medicinesType)
    },
    // 翻译处方类型
    prescriptionTypeFormatter(row) {
      return this.selectDictLabel(this.prescriptionTypeOptions, row.prescriptionType)
    },
    // 查询全部药品信息
    getMedicinesList() {
      this.loading = true
      listMedicinesForPage(this.queryParams).then(res => {
        this.medicinesTableList = res.data
        this.loading = false
        this.total = res.total
        this.$nextTick(() => {
          // 反选之前有的
          this.medicinesTableList.filter(r1 => {
            this.purchaseItemList.filter(r2 => {
              if (parseInt(r1.medicinesId) === parseInt(r2.medicinesId)) {
                this.$refs.medicinesTableList.toggleRowSelection(r1, true)
              }
            })
          })
        })
      })
    },
    // 选择添加药品搜索方法
    handleQuery() {
      this.getMedicinesList()
    },
    // 选择添加药品重置方法
    resetQuery() {
      this.resetForm('queryForm')
      this.getMedicinesList()
    },
    // 页面大小改变时触发
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      // 重新查询
      this.getMedicinesList()
    },
    // 换页时触发
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      // 重新查询
      this.getMedicinesList()
    },
    // 药品数据表格多选时触发
    handleSelectionChange(selection) {
      // console.log(selection)
      // 将用户当前选中的药品信息赋值
      this.selectMedicines = selection
      // 遍历用户当前选中的药品信息
      this.selectMedicines.filter(m1 => {
        // 标识用户之前是否已经选择过相同的药品信息
        // true表示已经选过 false表示之前没有选中过
        let flag = false
        // 遍历用户之前选中的药品信息
        this.purchaseItemList.filter(purchase => {
          // 判断用户当前选中的药品信息之前是否已经选中过
          // 若之前已经选中那么就不将当前选中的药品信息添加到
          // 选中药品信息列表中 反之则添加
          if (purchase.medicinesId === m1.medicinesId) {
            flag = true
          }
        })
        // 如果之前没有选中就添加
        if (!flag) {
          this.purchaseItemList.push(JSON.parse(JSON.stringify(m1)))
        }
      })

      // 剔除药品详情列表中不必要的属性
      this.purchaseItemList.filter(m => {
        this.$delete(m, 'status')
        this.$delete(m, 'medicinesStockNum')
        this.$delete(m, 'medicinesStockDangerNum')
        this.$delete(m, 'createTime')
        this.$delete(m, 'updateTime')
        this.$delete(m, 'createBy')
        this.$delete(m, 'updateBy')

        this.$set(m, 'purchaseNumber', m.purchaseNumber ? m.purchaseNumber : 1)
        this.$set(m, 'tradePrice', m.tradePrice ? m.tradePrice : 0.00)
        this.$set(m, 'tradeTotalAmount', m.tradeTotalAmount ? m.tradeTotalAmount : 0.00)
        this.$set(m, 'batchNumber', m.batchNumber ? m.batchNumber : '')
        this.$set(m, 'remark', m.remark ? m.remark : '')
      })
    },
    // 批量设置确认按钮
    // 批量设置就是设置采购详情的数量、批发价格、批次号、备注数据
    handleBatchSetSubmit() {
      // 向采购详情列表中设置数据
      this.purchaseItemList.filter(item => {
        item.purchaseNumber = this.batchSetForm.purchaseNumber
        item.tradePrice = this.batchSetForm.tradePrice
        item.batchNumber = this.batchSetForm.batchNumber
        item.remark = this.batchSetForm.remark
      })
      this.batchSetOpen = false
    },
    // 批量设置取消按钮
    cancelBatchSet() {
      this.batchSetOpen = false
    },
    // 删除
    handleDelele(index, row) {
      console.log(index, row.medicinesId)
      // 根据数组索引删除数组信息
      this.purchaseItemList.splice(index, 1)
    }
  }
}
</script>

<style scoped>
.box-card{
  padding: 0;
  margin: 0;
  margin-bottom: 8px;
}
</style>
